package Foo;

import static Foo.MainFrame.ENCODING;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;

/**
 * @author Blacko
 */
public class PanelVenta extends javax.swing.JPanel {

    List<String> Productos;
    DefaultTableModel model;

    public PanelVenta() {
        initComponents();
        cargaListaProductos();
        tablaListaProductos.getColumnModel().getColumn(0).setPreferredWidth(20);
        tablaListaProductos.getColumnModel().getColumn(1).setPreferredWidth(350);
        tablaListaProductos.getColumnModel().getColumn(2).setPreferredWidth(10);
        tablaListaProductos.getColumnModel().getColumn(3).setPreferredWidth(50);
        model = (DefaultTableModel) tablaListaProductos.getModel();
        campoProducto.grabFocus();
    }

    private void agregaFilaTabla(String texto) {
        for (Iterator<String> it = Productos.iterator(); it.hasNext();) {
            int cantidad = 0;
            String linea = it.next();
            String[] valores = linea.split(";");
            if (texto.equals(valores[0]) && valores[4].equals("Y")) {
                for (int i = 0; i < tablaListaProductos.getRowCount(); i++) {

                    if (model.getValueAt(i, 0).toString().equals(texto)) {
                        cantidad = Integer.parseInt(model.getValueAt(i, 2).toString());
                        model.removeRow(i);
                    }
                }
                cantidad = cantidad + Integer.parseInt(campoCantidad.getText().toString());
                model.addRow(new Object[]{
                    valores[0],
                    valores[1],
                    cantidad,
                    cantidad * Integer.parseInt(valores[2])
                });
            }
        }
        campoProducto.setText("");
        campoProducto.grabFocus();
        campoCantidad.setText("1");

        calcularTotal();
    }

    private void calcularTotal() {
        int total = 0;
        for (int i = 0; i < tablaListaProductos.getRowCount(); i++) {
            total = total + Integer.parseInt(model.getValueAt(i, 3).toString());
        }
        campoTotal.setText(String.valueOf(total));
    }

    private void cargaListaProductos() {
        Path path = Paths.get("./Config/ListaProductos.txt");
        try {
            Productos = Files.readAllLines(path, ENCODING);
        } catch (IOException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tablaListaProductos = new javax.swing.JTable();
        btnBorrar = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        btnSalir = new javax.swing.JButton();
        btnImprimir = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        campoProducto = new javax.swing.JTextField();
        campoTotal = new javax.swing.JLabel();
        campoCantidad = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();

        setBorder(javax.swing.BorderFactory.createCompoundBorder());
        setAutoscrolls(true);
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formKeyPressed(evt);
            }
        });

        tablaListaProductos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Codigo", "Producto", "Cant.", "Total"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.Integer.class, java.lang.Integer.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        tablaListaProductos.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_NEXT_COLUMN);
        jScrollPane1.setViewportView(tablaListaProductos);

        btnBorrar.setText("Borrar");
        btnBorrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBorrarActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Panel de Venta");

        jLabel2.setText("Total");

        btnSalir.setText("Salir");
        btnSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalirActionPerformed(evt);
            }
        });

        btnImprimir.setText("Imprimir Boleta");

        jLabel3.setText("Ingreso producto");

        campoProducto.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                campoProductoKeyPressed(evt);
            }
        });

        campoTotal.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        campoTotal.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        campoTotal.setText(" ");

        campoCantidad.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        campoCantidad.setText("1");
        campoCantidad.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                campoCantidadKeyReleased(evt);
            }
        });

        jLabel4.setText("Cant.");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(191, 191, 191)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 252, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnImprimir)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnSalir, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(campoTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(campoProducto, javax.swing.GroupLayout.PREFERRED_SIZE, 219, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(6, 6, 6)
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(campoCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 162, Short.MAX_VALUE)
                        .addComponent(btnBorrar, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnBorrar)
                    .addComponent(jLabel3)
                    .addComponent(campoProducto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(campoCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 185, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(campoTotal))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSalir)
                    .addComponent(btnImprimir))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void campoProductoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_campoProductoKeyPressed
        if (campoProducto.getText().length() > 0
                && campoCantidad.getText().length() > 0
                && evt.getKeyCode() == KeyEvent.VK_ENTER) {
            agregaFilaTabla(campoProducto.getText());
        }
    }//GEN-LAST:event_campoProductoKeyPressed

    private void btnBorrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBorrarActionPerformed
        try {
            model.removeRow(tablaListaProductos.getSelectedRow());
            calcularTotal();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }//GEN-LAST:event_btnBorrarActionPerformed

    private void btnSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalirActionPerformed
        System.exit(0);
    }//GEN-LAST:event_btnSalirActionPerformed

    private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed
        if (campoProducto.getText().length() > 0
                && campoCantidad.getText().length() > 0
                && evt.getKeyCode() == KeyEvent.VK_ENTER) {
            agregaFilaTabla(campoProducto.getText());
        }
    }//GEN-LAST:event_formKeyPressed

    private void campoCantidadKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_campoCantidadKeyReleased
        //JOptionPane.showMessageDialog(this, evt.getKeyCode());
        if (campoProducto.getText().length() > 0
                && campoCantidad.getText().length() > 0
                && evt.getKeyCode() == KeyEvent.VK_ENTER) {
            agregaFilaTabla(campoProducto.getText());
        } /*else if (evt.getKeyCode() == KeyEvent.VK_MINUS) {
            campoCantidad.setText(String.valueOf(Integer.parseInt(campoCantidad.getText()) - 1));
        } else if (evt.getKeyCode() == KeyEvent.VK_ADD) {
            campoCantidad.setText(String.valueOf(Integer.parseInt(campoCantidad.getText()) + 1));
        }*/
    }//GEN-LAST:event_campoCantidadKeyReleased

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBorrar;
    private javax.swing.JButton btnImprimir;
    private javax.swing.JButton btnSalir;
    private javax.swing.JTextField campoCantidad;
    private javax.swing.JTextField campoProducto;
    private javax.swing.JLabel campoTotal;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tablaListaProductos;
    // End of variables declaration//GEN-END:variables
}
